package cn.gqr.dao;

import cn.gqr.entity.Type;
import cn.gqr.uitl.SessionUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TypeDao {

    @Autowired
    MongoTemplate mT;

    //获取所有分类
    public List<Type> getTypeAll(){
        List<Type> types = mT.findAll(Type.class);
        return types;
    }

    //获取所有分类2
    public List<Type> findByPage(int start){
        Pageable of = PageRequest.of(start<0?0:start, 5);
        Query q = new Query().with(of);
        List<Type> types = mT.find(q,Type.class);
        return types;
    }

    //获取总行数
    public long findByPageCount(){
        return mT.count(new Query(),Type.class);
    }

    //根据id获取分类
    public Type findById(String id){
        Criteria c = new Criteria();
        Type type = mT.findOne(new Query(c.where("id").is(id)), Type.class);
        return type;
    }

    //根据id删除分类
    public boolean del(String id){
        Criteria c = new Criteria();
        boolean b = mT.remove(new Query(c.where("id").is(id)), Type.class).wasAcknowledged();
        return b;
    }

    //添加分类
    public Type add(Type type){
        Type t = mT.insert(type);
        return t;
    }

    //根据id修改分类名称
    public boolean upByIdType(Type type){
        Criteria c = new Criteria().where("id").is(type.getId());
        Update u = new Update().set("type", type.getType());
        return mT.updateFirst(new Query(c),u,Type.class).wasAcknowledged();
    }

    //根据id修改分类数量加一或者减一
    //参数b true = 数量加一   false = 数量减一
    public boolean upByIdNum(Type type,boolean b){
        Criteria c = new Criteria().where("id").is(type.getId());
        int num = b?type.getNum()+1:type.getNum()-1;
        Update u = new Update().set("num", num);
        return mT.updateFirst(new Query(c),u,Type.class).wasAcknowledged();
    }

}
